<?php
/**
 * CategoriesModel
 * @author   songhuan <iphper@yeah.net>
 * @version   $Id: CategoriesModel.php 1 2011-06-19 00:00:00Z $
 */
class CategoriesModel extends CMysqlTable
{
	public static function model($className = __CLASS__)
	{
		return parent::model($className);
	}
	
	public $relations = array(
		'Posts' => array(self::HAS_MANY, 'Posts', 'category_id')
	);
	
	public $rules = array(
		'category_name' => array(
			'required' => true,	
			'unique' => true, 
			'when' => self::BOTH
		)
	);
	
	public $messages = array(
		'category_name' => array(
			'required' => '请填写类别名',
			'unique' => '此类别名已被使用，请更换类别名'
		)
	);
	
	public function countPosts()
	{
		$condition = 'category_id = ? AND post_status != ?';
		$params = array('category_id' => $this->category_id, 'post_status' => 't');
		return PostsModel::model()->countByCondition($condition, $params);
	}
	
	/**
	 * 无限级分类, 获取类别<select>框中的option串
	 * @param integer $pid 类别父ID.
	 * @param integer $id 类别ID.
	 * @param string $pad 填充字符串.
	 * @return string option
	 */
	public function options($pid = 0, $id = 0, $pad = '')
	{
		$models = $this->setSelectFields(array('category_id', 'category_pid', 'category_name'))->findAll('category_pid = ? ORDER BY menu_order', $pid);
		
		$option = '';
		foreach ($models as $key => $model)
		{
			$selected = ($id == $model->category_id) ? ' selected' : '';
			$option .= "<option value=\"{$model->category_id}\"$selected>$pad{$model->category_name}</option>\r\n";
			$option .= $this->options($model->category_id, $id, $pad . '&nbsp;&nbsp;&nbsp;&nbsp;');
		}
		return $option;
	}
	
	/**
	 * 无限级分类, 类别列表
	 * @param integer $pid 类别父ID.
	 * @param integer $step 层.
	 * @param array $rows 类别.
	 * @param array $css 类别<tr>上的css名.
	 */
	public function lists($pid = 0, $step = -1, &$rows, &$css)
	{
		$models = $this->findAll('category_pid = ? ORDER BY menu_order', $pid);
		
		$step++;
		foreach ($models as $key => $model)
		{
			if ($step > 0)
			{
				$c = $this->countByAttributes(array('category_pid' => $model->category_id)) > 0 ? '3' : '2';
				$css[] = 'node-c' . $c . '-' . $step;
			}
			else 
				$css[] = 'editlinktip hasTip';
			
			$rows[] = $model;
			$this->lists($model->category_id, $step, $rows, $css);	
		}
	}
}
